package com.atguigu.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constants.ProductConstant;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.product.dao.SpuInfoDao;
import com.atguigu.product.entity.*;
import com.atguigu.product.feign.CouponFeignService;
import com.atguigu.product.feign.SearchFeignService;
import com.atguigu.product.feign.WareFeignService;
import com.atguigu.product.service.*;
import com.atguigu.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService saleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        //1. 保存spu基本信息pms_spu_info

        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.save(infoEntity);


        //2. 保存spu的描述图片pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descript = new SpuInfoDescEntity();
        descript.setSpuId(infoEntity.getId());
        descript.setDecript(String.join(",", decript));
        spuInfoDescService.save(descript);

        //3. 保存spu的图片集pms_spu_images
        List<String> images = vo.getImages();
        if (images != null && images.size() != 0) {

            List<SpuImagesEntity> spuImagesEntities = images.stream().map((image) -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(infoEntity.getId());
                spuImagesEntity.setImgUrl(image);
                return spuImagesEntity;
            }).collect(Collectors.toList());

            spuImagesService.saveBatch(spuImagesEntities);

        }


        //4. 保存spu的规格参数pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map((attr) -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            attrValueEntity.setSpuId(infoEntity.getId());
            attrValueEntity.setAttrId(attr.getAttrId());
            attrValueEntity.setAttrValue(attr.getAttrValues());
            attrValueEntity.setQuickShow(attr.getShowDesc());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            attrValueEntity.setAttrName(attrEntity.getAttrName());

            return attrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);


        //  5. 保存spu的积分信息gulimall_sms->sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(infoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }


        // 6. 保存spu对应的所有sku信息
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {

            skus.forEach((sku -> {
                String defaultImg = "";
                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }

                SkuInfoEntity spuInfo = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, spuInfo);
                spuInfo.setSpuId(infoEntity.getId());
                spuInfo.setBrandId(infoEntity.getBrandId());
                spuInfo.setCatalogId(infoEntity.getCatalogId());
                spuInfo.setSaleCount(0L);
                spuInfo.setSkuDefaultImg(defaultImg);
                //1.)   sku的基本信息pms_sku_info
                skuInfoService.save(spuInfo);


                Long skuId = spuInfo.getSkuId();
                List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().map((img) -> {

                            SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                            skuImagesEntity.setSkuId(skuId);
                            skuImagesEntity.setDefaultImg(img.getDefaultImg());
                            skuImagesEntity.setImgUrl(img.getImgUrl());
                            return skuImagesEntity;

                        })
                        // 没有图片路径的无需保存
                        .filter(item -> {
                            //返回true就是需要，fasle就是剔除
                            return StringUtils.isNotEmpty(item.getImgUrl());
                        })
                        .collect(Collectors.toList());


                //2.)   sku的图片信息pms_sku_images
                skuImagesService.saveBatch(skuImagesEntities);


                List<Attr> saleAttr = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = saleAttr.stream().map((attr) -> {

                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;

                }).collect(Collectors.toList());

                //3.)   sku的销售属性信息pms_sku_sale_attr_value
                saleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //4.)   sku的优惠、满减等信息gulimall_sms->sms_sku_ladder
                // sms_sku_full_reduction
                // sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存优惠信息失败");
                    }
                }


            }));
        }


    }


    /**
     * Spu检索
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        LambdaQueryWrapper<SpuInfoEntity> queryWrapper = new LambdaQueryWrapper<>();

        //1. 查询条件-> 分类id
        String catelogId = (String) params.get("catelogId");
        //判断分类id是不为空， 并且不为0
        if (StringUtils.isNotEmpty(catelogId) && !("0".equalsIgnoreCase(catelogId))) {
            queryWrapper.eq(SpuInfoEntity::getCatalogId, catelogId);
        }

        //2. 查询条件-> 品牌id
        String brandId = (String) params.get("brandId");
        //判断牌id是不为空， 并且不为0
        if (StringUtils.isNotEmpty(brandId) && !("0".equalsIgnoreCase(brandId))) {
            queryWrapper.eq(SpuInfoEntity::getBrandId, brandId);
        }

        //3. 查询条件-> 状态
        String status = (String) params.get("status");
        //判断牌id是不为空， 并且不为0
        if (StringUtils.isNotEmpty(status)) {
            queryWrapper.eq(SpuInfoEntity::getPublishStatus, status);
        }

        //4. 检索字段
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.and(k -> {
                k.eq(SpuInfoEntity::getId, key).or().like(SpuInfoEntity::getSpuName, key);
            });
        }

        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), queryWrapper);


        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        //根据spuId查询对应的所有sku信息、品牌的名字
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);

        // 查询skuId的集合
        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //TODO 4、查询当前sku的所有规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseListforspuById(spuId);
        List<Long> attrIds = baseAttrs.stream().map(
                attr -> {
                    return attr.getAttrId();
                }
        ).collect(Collectors.toList());

        List<Long> searchAttrIds =attrService.selectSearchAttrs(attrIds);
        //转换为set集合
        HashSet<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attr> attrList = baseAttrs.stream().filter(item -> {
                            return idSet.contains(item.getAttrId());
                        }
                )
                .map(item -> {
                    SkuEsModel.Attr attr = new SkuEsModel.Attr();
                    BeanUtils.copyProperties(item, attr);
                    return attr;
                })
                .collect(Collectors.toList());

        //hasStocl, hotScore
        //TODO 1、发送远程调用， 库存系统查询是否有库存(true/false)

        R skuHasStock = null;
        Map<Long, Boolean> stockMap=null;
        try {
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            skuHasStock = wareFeignService.getSkuHasStock(skuIdList);
            stockMap = skuHasStock.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常，原因{}",e);
        }


        //2. 封装每个Sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            //封装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, esModel);

            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());

            //设置库存信息
            esModel.setHasStock(finalStockMap == null ? true : finalStockMap.get(sku.getSkuId()));

            //TODO 2、热度评分,0
            esModel.setHotScore(0L);
            //TODO 3、查询品牌和分类的名字信息
            //brandName, brandImg. catelogName, attrs
            BrandEntity brand = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brand.getName());
            esModel.setBrandImg(brand.getLogo());

            CategoryEntity category = categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogId(category.getCatId());
            esModel.setCatalogName(category.getName());
            esModel.setAttrs(attrList);
            return esModel;

        }).collect(Collectors.toList());

        //TODO 5、将数据发送给es进行保存, gulimall-search
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode()==0) {
            //远程调用成功
            //TODO 6、修改当前spu的状态
            this.baseMapper.upSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            //远程调用失败
            //TODO 7重复调用？接口幂等性； 重试机制？
            log.error("商品远程es保存失败");
        }

    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {

        SkuInfoEntity skuInfo = skuInfoService.getById(skuId);
        SpuInfoEntity spuInfo = this.getById(skuInfo.getSpuId());
        return spuInfo;

    }

}